﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Config;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Test
{
    public class Program
    {
        private static void Main(string[] args)
        {
           // var context = new KeyCoreDbContext();
            //Database.SetInitializer<KeyCoreDbContext>(null);
            var conf = new DbMigratorConfig();
            var migrator = new DbMigrator(conf);
            var scripter = new MigratorScriptingDecorator(migrator);
           // List<string> pm = migrator.GetPendingMigrations().ToList();

            // migrator.Update(null);
            foreach (string migration in migrator.GetPendingMigrations())
            {
                var sql = new MigratorScriptingDecorator(migrator).ScriptUpdate(null, migration);
                Console.WriteLine(sql);
            }

            using (var dc = new KeyCoreDbContext())
            {
                Console.WriteLine(dc.Database.Exists());
                dc.Database.Initialize(true);
                Console.Write(dc.Database.Exists());

            }
        }
    }

    public class DbConfig : DbConfiguration
    {
        public DbConfig()
        {

#if DEBUG
            SetDatabaseInitializer(new CreateDatabaseIfNotExists<KeyCoreDbContext>());
#else
                SetDatabaseInitializer(null);
#endif

            // SetDefaultConnectionFactory(new SqlConnectionFactory();
        }
    }

    public class DbMigratorConfig : DbMigrationsConfiguration<KeyCoreDbContext>
    {
        public DbMigratorConfig()
        {
            string constr = @"Data Source=(localdb)\v11.0;AttachDBFilename=|DataDirectory|\unittestdb.mdf";
            string invpr = "System.Data.SqlClient";
            //   AutomaticMigrationsEnabled = true;
            TargetDatabase = new DbConnectionInfo(constr, invpr);
           // MigrationsAssembly = typeof (KeyCoreDbContext).Assembly;
          //  ContextType = typeof (KeyCoreDbContext);
        }
    }

    public class User
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        //public virtual string Name2 { get; set; }
    }

    public class KeyCoreDbContext : DbContext
    {
        public DbSet<User> Type { get; set; }
    }
} 